﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

public partial class _Default : System.Web.UI.Page {

    protected void Page_Load(object sender, EventArgs e) {
        if (!this.IsPostBack) {
            foreach (MembershipProvider p in Membership.Providers) {
                this.ProviderNameList.Items.Add(p.Name);
            }
        }
    }

    protected void TestButton_Click(object sender, EventArgs e) {
        // Find provider
        var p = Membership.Providers[this.ProviderNameList.SelectedValue];

        // Create random user data
        var r = Guid.NewGuid().ToString("N").Substring(0, 8);
        var userName = "TestUser_" + r;
        var email = "testuser_" + r + "@example.com";
        var password = Membership.GeneratePassword(7, 1);
        object providerUserKey = null;

        if (p.Name.Equals("TableMembershipProvider_EmailAddressAsUserName")) {
            // Use e-mail address as user name
            userName = email;
        }
        else if (p.Name.Equals("TableMembershipProvider_CustomGuids")) {
            // Create custom keys
            providerUserKey = Guid.NewGuid();
        }

        // Create user
        MembershipCreateStatus status;
        var newUser = p.CreateUser(
            userName,           // user name
            password,           // password
            email,              // e-mail address
            null,               // question
            null,               // answer
            true,               // approved
            providerUserKey,    // provider key
            out status);
        if (status != MembershipCreateStatus.Success) {
            throw new Exception("Membership provider returned: " + status.ToString());
        }

        // Display results
        this.UserNameLabel.Text = newUser.UserName;
        this.PasswordLabel.Text = password;
        this.EmailLabel.Text = newUser.Email;
        this.ProviderUserKeyLabel.Text = newUser.ProviderUserKey.ToString();
    }

}